﻿using System.Runtime.Serialization;
using MediaBrowser.Library.Entities;
using MediaBrowser.Library;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;

namespace MediaBrowserWS.Service.Classes
{
    [DataContract]
    public class MetadataItem : BasicItem
    {
        public MetadataItem(BaseItem item)
            : base(item)
        {
            Overview = item.Overview;
            DateModified = item.DateModified;
            CustomRating = item.CustomRating;
            if (item is IShow)
            {
                IShow show = item as IShow;
                ImdbRating = show.ImdbRating;
                ProductionYear = show.ProductionYear;
                RunningTime = show.RunningTime;
                Genres = show.Genres;
            }

            if (Type == Enums.MediaTypes.Movie)
            {
                SetMovieId(item);
            }
        }

        private void SetMovieId(BaseItem item)
        {
            string myMoviesXml = Path.Combine(item.Path, "mymovies.xml");
            if (File.Exists(myMoviesXml))
            {
                XDocument doc = XDocument.Load(myMoviesXml);

                var tmdbNode = doc.Descendants("TMDbId").FirstOrDefault();
                var imdbNode = doc.Descendants("IMDB").FirstOrDefault();

                if (tmdbNode != null)
                {
                    TmdbId = tmdbNode.Value;
                }

                if (imdbNode != null)
                {
                    ImdbId = imdbNode.Value;
                }
            }
        }

        [DataMember]
        public string Overview { get; private set; }

        [DataMember]
        public DateTime DateModified { get; private set; }

        [DataMember(EmitDefaultValue = false)]
        public float? ImdbRating { get; private set; }

        [DataMember(EmitDefaultValue = false)]
        public string CustomRating { get; private set; }

        [DataMember(EmitDefaultValue=false)]
        public int? ProductionYear { get; private set; }

        [DataMember(EmitDefaultValue = false)]
        public int? RunningTime { get; private set; }

        [DataMember]
        public IEnumerable<string> Genres { get; private set; }

        [DataMember(EmitDefaultValue=false)]
        public string ImdbId { get; private set; }

        [DataMember(EmitDefaultValue = false)]
        public string TmdbId { get; private set; }
    }
}
